package com.jame.basics.thread.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * @author : Jame
 * @date : 2021-01-10 16:16
 **/
public class ConditionTest {
    public static void main(String[] args) {
        Calculate2 calculate = new Calculate2();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    calculate.add();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "A").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    calculate.reduce();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "B").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    calculate.add();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "C").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    calculate.reduce();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "D").start();

    }
}

class Calculate2 {
    int i = 0;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();


    //增加方法
    public void add() throws InterruptedException {
        lock.lock();
        try {
            //if判断会出现虚假唤醒,wait等待后被唤醒会直接走出if执行下面代码,而while会重复判断
            while (i != 0) {
                //需要等待
                condition.await();
            }
            //增加
            i++;
            System.out.println(Thread.currentThread().getName() + "==" + i);
            //唤醒其他线程
            condition.signalAll();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
           lock.unlock();
        }
    }

    //减少方法
    public  void reduce() throws InterruptedException {
        lock.lock();
        try {
            while (i == 0) {
                condition.await();
            }
            i--;
            System.out.println(Thread.currentThread().getName() + "==" + i);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
         lock.unlock();
        }

    }

}
